import { defineStore } from "pinia";
import { getMbSize, getfilesize } from "@util/index"
import { getFileType, getFileName, solveTimeStamp } from "@util/index"
import axios, { type UploadSuccess } from '@util/http'
import { showSuccessAlert, showErrorAlert } from '@util/showAlert'

export enum UseFile {
  "pjp", "xbm", "ico",
  "bmp", "jpg", "jpeg",
  "png", "tif", "gif",
  "pcx", "tga", "exif",
  "fpx", "svg", "cdr",
  "pcd", "dxf", "ufo",
  "eps", "raw", "WMF",
  "webp", "avif", "apng"
}

export interface FileItem {
  name: string,
  type: string,
  size: string,
  oversize: boolean
  base64: string,
  width: number,
  height: number,
  expired: string,
  originFile: File
}

export const useFileStore = defineStore("file", () => {
  const uploadList = reactive<FileItem[]>([])
  let uploaded = reactive<string[]>([])

  // 1 将文件列表存进 uploadList
  function saveFile(fileArr: File[]) {
    fileArr.forEach((file: File) => {
      let target: Partial<FileItem> = {}
      // 基础信息
      target.name = getFileName(file.name)
      target.type = getFileType(file.name)
      target.size = getfilesize(file.size)
      target.oversize = getMbSize(file.size) > 6 ? true : false
      target.expired = ""
      target.originFile = file

      // 当 size 过大时不再读取
      if (target.oversize) {
        showErrorAlert(`${target.name} 文件过大`, `${target.name} file oversize`)
        return
      }

      // 读取 base64
      const reader = new FileReader();
      reader.readAsDataURL(file);
      // 读取完成后触发
      reader.onload = () => {
        target.base64 = reader.result as string
        // 获取图片宽高
        const image = new Image()
        image.src = target.base64
        image.onload = () => {
          target.width = image.width
          target.height = image.height
          // 将对象存进数组
          uploadList.push(target as FileItem)
        };
      }
    })
  }

  // 2 将文件从文件列表移除
  function deleteFile(index: number) {
    uploadList.splice(index, 1)
  }

  // 3 删除刚刚上传的列表
  function deleteUploadedFile(filename: string) {
    let index = uploaded.indexOf(filename)
    if (index >= 0) uploaded.splice(index, 1);
  }

  // 4 上传文件
  function uploadFile() {
    const formData = new FormData();
    let expired = ""
    // 添加文件
    uploadList.map(target => {
      formData.append('img', target.originFile, target.name);
      // 添加过期时间
      if (target.expired != "*") {
        expired += solveTimeStamp(target.expired) + ','
      } else {
        expired += `${target.expired},`
      }
    })
    formData.append('time', expired)

    // 发送请求
    axios.post<any, UploadSuccess>("/upload", formData).then(res => {
      if (res.status === 'success') {
        showSuccessAlert("上传文件成功", "Upload File Success")
        uploaded.push(...res.data)
        // 清空 uploadList 数组
        uploadList.length = 0
      }
    }, err => {
      import.meta.env.MODE === "production" ? showErrorAlert("上传文件失败", "Upload File Error") : showErrorAlert(err, "Upload File Error")
    })
  }

  // 监听 uploadList，当重新填充数据时清空已经上传的数组
  watch(uploadList, (newV) => {
    if (newV.length != 0) uploaded.length = 0;
  })

  return { uploadList, uploaded, uploadFile, deleteFile, saveFile, deleteUploadedFile }
})

